package com.xjx.programmer.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.xjx.programmer.mapper.ToolSqlConnectionMapper;
import com.xjx.programmer.model.ToolSqlConnection;
import com.xjx.programmer.model.ExecuteResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 数据库连接管理服务
 */
@Slf4j
@Service
public class ToolSqlConnectionService {

    @Autowired
    private ToolSqlConnectionMapper toolSqlConnectionMapper;

    /**
     * 保存数据库连接
     */
    public ExecuteResult saveConnection(ToolSqlConnection connection) {
        try {
            // 设置创建和修改时间
            connection.setGmtCreate(LocalDateTime.now());
            connection.setGmtModified(LocalDateTime.now());
            
            int rows = toolSqlConnectionMapper.insert(connection);
            
            if (rows > 0) {
                Map<String, Object> resultData = new HashMap<>();
                resultData.put("id", connection.getId());
                return ExecuteResult.builder()
                        .success(true)
                        .message("保存连接成功")
                        .data(List.of(resultData))
                        .build();
            } else {
                return ExecuteResult.builder()
                        .success(false)
                        .message("保存连接失败")
                        .errorMessage("插入数据失败")
                        .build();
            }
            
        } catch (Exception e) {
            log.error("保存数据库连接失败", e);
            return ExecuteResult.builder()
                    .success(false)
                    .message("保存连接失败")
                    .errorMessage(e.getMessage())
                    .build();
        }
    }

    /**
     * 根据账户查询连接列表
     */
    public ExecuteResult getConnectionsByAccount(Long accountNo) {
        try {
            LambdaQueryWrapper<ToolSqlConnection> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ToolSqlConnection::getAccountNo, accountNo)
                       .orderByDesc(ToolSqlConnection::getGmtCreate);
            
            List<ToolSqlConnection> connections = toolSqlConnectionMapper.selectList(queryWrapper);
            
            // 转换为Map格式
            List<Map<String, Object>> dataList = connections.stream()
                    .map(this::convertToMap)
                    .collect(Collectors.toList());
            
            return ExecuteResult.builder()
                    .success(true)
                    .message("查询成功")
                    .data(dataList)
                    .build();
                    
        } catch (Exception e) {
            log.error("查询数据库连接失败", e);
            return ExecuteResult.builder()
                    .success(false)
                    .message("查询失败")
                    .errorMessage(e.getMessage())
                    .build();
        }
    }

    /**
     * 根据ID查询连接详情
     */
    public ExecuteResult getConnectionById(Long id) {
        try {
            ToolSqlConnection connection = toolSqlConnectionMapper.selectById(id);
            
            if (connection == null) {
                return ExecuteResult.builder()
                        .success(false)
                        .message("连接不存在")
                        .errorMessage("未找到指定的连接记录")
                        .build();
            }
            
            return ExecuteResult.builder()
                    .success(true)
                    .message("查询成功")
                    .data(List.of(convertToMap(connection)))
                    .build();
                    
        } catch (Exception e) {
            log.error("查询数据库连接详情失败", e);
            return ExecuteResult.builder()
                    .success(false)
                    .message("查询失败")
                    .errorMessage(e.getMessage())
                    .build();
        }
    }

    /**
     * 删除数据库连接
     */
    public ExecuteResult deleteConnection(Long id, Long accountNo) {
        try {
            LambdaQueryWrapper<ToolSqlConnection> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ToolSqlConnection::getId, id)
                       .eq(ToolSqlConnection::getAccountNo, accountNo);
            
            int rows = toolSqlConnectionMapper.delete(queryWrapper);
            
            if (rows > 0) {
                return ExecuteResult.builder()
                        .success(true)
                        .message("删除连接成功")
                        .build();
            } else {
                return ExecuteResult.builder()
                        .success(false)
                        .message("删除连接失败")
                        .errorMessage("连接不存在或无权限删除")
                        .build();
            }
            
        } catch (Exception e) {
            log.error("删除数据库连接失败", e);
            return ExecuteResult.builder()
                    .success(false)
                    .message("删除连接失败")
                    .errorMessage(e.getMessage())
                    .build();
        }
    }

    /**
     * 更新数据库连接
     */
    public ExecuteResult updateConnection(ToolSqlConnection connection) {
        try {
            // 设置修改时间
            connection.setGmtModified(LocalDateTime.now());
            
            LambdaUpdateWrapper<ToolSqlConnection> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(ToolSqlConnection::getId, connection.getId())
                        .eq(ToolSqlConnection::getAccountNo, connection.getAccountNo())
                        .set(ToolSqlConnection::getConnectName, connection.getConnectName())
                        .set(ToolSqlConnection::getConnectDbType, connection.getConnectDbType())
                        .set(ToolSqlConnection::getHost, connection.getHost())
                        .set(ToolSqlConnection::getPort, connection.getPort())
                        .set(ToolSqlConnection::getUrl, connection.getUrl())
                        .set(ToolSqlConnection::getPassword, connection.getPassword())
                        .set(ToolSqlConnection::getUsername, connection.getUsername())
                        .set(ToolSqlConnection::getDbName, connection.getDbName())
                        .set(ToolSqlConnection::getGmtModified, connection.getGmtModified());
            
            int rows = toolSqlConnectionMapper.update(null, updateWrapper);
            
            if (rows > 0) {
                return ExecuteResult.builder()
                        .success(true)
                        .message("更新连接成功")
                        .build();
            } else {
                return ExecuteResult.builder()
                        .success(false)
                        .message("更新连接失败")
                        .errorMessage("连接不存在或无权限更新")
                        .build();
            }
            
        } catch (Exception e) {
            log.error("更新数据库连接失败", e);
            return ExecuteResult.builder()
                    .success(false)
                    .message("更新连接失败")
                    .errorMessage(e.getMessage())
                    .build();
        }
    }

    /**
     * 将ToolSqlConnection转换为Map
     */
    private Map<String, Object> convertToMap(ToolSqlConnection connection) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", connection.getId());
        map.put("accountNo", connection.getAccountNo());
        map.put("accountUsername", connection.getAccountUsername());
        map.put("connectName", connection.getConnectName());
        map.put("connectDbType", connection.getConnectDbType());
        map.put("host", connection.getHost());
        map.put("port", connection.getPort());
        map.put("url", connection.getUrl());
        map.put("password", connection.getPassword());
        map.put("username", connection.getUsername());
        map.put("dbName", connection.getDbName());
        map.put("gmtCreate", connection.getGmtCreate());
        map.put("gmtModified", connection.getGmtModified());
        return map;
    }

}
